package cn.sytton.taffecloud.common.minio.util;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * OutputStream工具类
 *
 * @author skyrock
 */
@Slf4j
public class OutputStreamUtil {
    /**
     * 设置下载response头属性
     * @param response
     * @param filename
     * @param length
     */
    public static void setDownloadHeader(HttpServletResponse response, String filename, long length) {
        setDownloadHeader(response, filename, length, true);
    }

    /**
     * 设置下载response头属性
     * @param response
     * @param filename
     * @param length
     */
    public static void setDownloadHeader(HttpServletResponse response, String filename, long length, boolean isOctetStream ) {
        String name;
        try {
            name = URLEncoder.encode(filename, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            log.error("文件名编码错误:"+e.getMessage(), e);
            name = filename;
        }
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.addHeader("Content-Disposition", "attachment;filename=" + name);
        if (isOctetStream) {
            response.setContentType("application/octet-stream");
        }
        if (length > 0) {
            response.addHeader("Content-Length", "" + length);
        }
    }
}
